package com.example.intelligentattendancesystem.service.impl;

import com.example.intelligentattendancesystem.mapping.UserMapping;
import com.example.intelligentattendancesystem.pojo.User;
import com.example.intelligentattendancesystem.service.FileUpService;
import com.example.intelligentattendancesystem.service.IndexService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import static com.example.intelligentattendancesystem.Utils.Constant.USER_LOGIN_KEY;

@Service
public class IndexServiceImpl implements IndexService {
    public IndexServiceImpl() {
        super();
    }
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    UserMapping userMapping;
    @Autowired
    FileUpService fileUpService;

    @Override
    public User loginService(int userId, String password) {
        User user = userMapping.selectUserByUserId(userId);
        if(user==null){
            return null;
        }
        if (user.getPassword().equals(password)){
            return user;
        }
        return null;
    }

    @Override
    public boolean registerService(User user) {
        User user1 = userMapping.selectUserByUserId(user.getUserId());
        if(user1!=null){
            return false;
        }
        int count  = userMapping.insertUser(user);
        if (count == 0)
            return false;
        //设置默认头像

        File file = new File("static/boshimao.jpg");

        //File文件转MultipartFile
        FileInputStream input = null;
        MultipartFile multipartFile=null;
        try {
            input = new FileInputStream(file);
            multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        fileUpService.upFileService(multipartFile,user.getUserId());
        return true;
    }

    @Override
    public void logoffService(int userId) {
        userMapping.deleteUserByUserId(userId);
    }

    @Override
    public void logoutService(int userId) {

    }
}
